<?php
/**
 * 后台用控制器模板
 */
namespace app\admin\controller\maintain;

use app\admin\controller\AuthController;
use service\JsonService;

class Agreement extends AuthController
{
	public $model = '\app\common\model\Agreement';

    use \traits\ShotcutControllerTrait;


    /**
     * [_index description]
     * @Author   FW
     * @DateTime 2021-05-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function index()
    {
    	return $this->add($this->model::FIXED_ID);
    }

    public function add( $id = 0 )
    {
        $data = $this->model::getOne($id) ?? ['id' => $id];
        $this->assign('data' , json_encode($data));
        return $this->fetch('add');
    }

    /**
     * [_save description]
     * @Author   FW
     * @DateTime 2021-05-10
     * @Email    123763712@qq.com
     * @param    array            $data [description]
     * @return   [type]                 [description]
     */
    protected function _save( array $data )
    {
    	if ( !isset($data['id']) || $data['id'] <= 0 ) {
    		$data['create_time'] = date('Y-m-d H:i:s');
    		$data['create_by']   = $this->adminInfo['real_name'];
    	}
    	$data['update_time'] = date('Y-m-d H:i:s');
    	$data['update_by']   = $this->adminInfo['real_name'];

        return $data;
    }

    /**
     * 保存
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function save()
    {
        $data = $this->request->post();

        $this->model::beginTrans();

        try {
            ## 自定义保存数据的额外操作
            $data = $this->_save($data);

            if ( !empty($data) && is_array($data) ) {
                /** 自动补全机构ID和校区ID */
                if ( !isset($data['org_id']) ) {
                    $data['org_id'] = $this->model::getBelongOrganId();
                }

                $res  = $this->model::saveOne($data);

                if ( $res !== false ) {
                    $this->model::commitTrans();
                    return JsonService::successful('操作成功!');
                }
            }
        } catch (\Exception $e ) {
            $this->model::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return JsonService::fail('操作失败');
    }
}
